package com.atguigu.gmall.user.service.impl;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.user.vo.LoginRespVo;
import com.atguigu.gmall.user.vo.LoginVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.user.entity.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author lfy
 * @description 针对表【user_info(用户表)】的数据库操作Service实现
 * @createDate 2023-08-29 11:43:55
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
        implements UserInfoService {


    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public LoginRespVo login(LoginVo loginVo) {
        String loginName = loginVo.getLoginName();
        String passwd = loginVo.getPasswd();

        UserInfo info = lambdaQuery()
                .eq(UserInfo::getLoginName, loginName)
                .eq(UserInfo::getPasswd, MD5.encrypt(passwd))
                .one();

        if (info == null) {
            //查无此用户
            throw new GmallException(ResultCodeEnum.USER_PWD_INVAILD);
        }


        //1、上面登录成功
        String token = UUID.randomUUID().toString().replace("-", "");

        //组装给前端的数据
        LoginRespVo respVo = new LoginRespVo();
        respVo.setToken(token);
        respVo.setNickName(info.getNickName());
        respVo.setUserId(info.getId());
        respVo.setName(info.getName());

        //2、绑定当前token和用户关系； 完成7天免登录
        // 登录成功以后：1）、前端收到的令牌前端自己存7天，  2）、服务端配合前端这个令牌存7天
        redisTemplate.opsForValue().set(RedisConst.LOGIN_USER +token,
                JSONs.toJSONStr(info),7, TimeUnit.DAYS);


        return respVo;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(RedisConst.LOGIN_USER+token);
    }
}




